package cn.xiaou.view;


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.JTableHeader;

import cn.xiaou.domain.Transaction;
import cn.xiaou.domain.User;
import cn.xiaou.domain.UserReal;
import cn.xiaou.draw.MyDefaultTableModel;
import cn.xiaou.draw.MyJButtom;
import cn.xiaou.draw.MyScrollBarUI;
import cn.xiaou.draw.MyTextFieldBorder;
import cn.xiaou.service.UserService;
import cn.xiaou.service.impl.UserServiceImpl;
import cn.xiaou.utils.ImageManagerUtils;

public class PsersonStock extends JFrame implements ActionListener{
	private static final long serialVersionUID = 1L;
	private JTable	table;
	private MyDefaultTableModel stock;
	/*private JButton nextPage;
	private JButton previousPage;*/
	private JLabel stockCode;
	private JLabel stockname;
	private JLabel stockCount;
	private JTextField stockBuyCount;
	private JButton buy,back;
	private UserService userService = new UserServiceImpl();
	private	String [] selectStock = new String [5];
	private Double money;
	private User user;
	private JFrame mainFrame;
	public PsersonStock(User user,JFrame mianFrame) {
		this.mainFrame=mianFrame;
		this.user = user;
		/*setAlwaysOnTop(true);*/
		setSize(969, 700);
		setLocationRelativeTo(null);
		setResizable(false);
		setUndecorated(true);
	    setBackground(new Color(0,0,0,0));
	    setIconImage(getToolkit().getImage(ImageManagerUtils.icoUrl));
		//------------------------------------------------------------------
		 ImageIcon background = new ImageIcon(ImageManagerUtils.black);
		 JLabel bg = new JLabel(background);
		 bg.setBounds(0, 0, background.getIconWidth(),background.getIconHeight());
		 JPanel panel = (JPanel) getContentPane(); 
		 //设置透明
		 panel.setOpaque(false);
		 //将背景图的label置于窗体的底层
		 getLayeredPane().add(bg, new Integer(Integer.MIN_VALUE)); 
		 panel.setLayout(null);
		//------------------------------------------------------------------
		 JPanel panel2 = new JPanel();
		 panel2.setBounds(-12, 0, 1000, 500);
		 panel2.setOpaque(false);
		 
		 	//表头
	        String[] columnName = { "单号","股票代码", "股票名称", "最新价格", "持有股数","总价","状态" };
	        // 创建一个默认的表格模型
	        stock = new MyDefaultTableModel();
	        stock.setColumnIdentifiers(columnName);
	        table = new JTable(stock);
	      //---------------------准备数据-----------------------
	        
	        Runnable runnable = new Runnable() {  
	            public void run() {  
	            	data();
	            }  
	        };  
	        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); 
	        service.scheduleAtFixedRate(runnable, 0, 15, TimeUnit.SECONDS);  
	        //----------------------------------------------------
	        table.setPreferredScrollableViewportSize(new Dimension(980, 496));
	        //只能选中单个
	        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	        table.getTableHeader().setFont(new Font("黑体", 0, 15));
	        table.setFont(new Font("Menu.font", Font.PLAIN, 20));
	        table.getTableHeader().setReorderingAllowed(false); 
	        table.getTableHeader().setResizingAllowed(false);
	        table.setRowHeight(30);
	        //表头的设置
	        JTableHeader tableH = table.getTableHeader();
	        tableH.setBackground(Color.BLACK);
	        tableH.setForeground(Color.WHITE);
	        
	        //滚动条
	        JScrollPane s = new JScrollPane(table);
	        s.getVerticalScrollBar().setUI(new MyScrollBarUI());
	        //滚动条背景色
	        s.setBackground(Color.red); 
	        
	        panel2.add(s);
	        panel.add(panel2);
	        //单机选中返回
	        table.addMouseListener(new MouseAdapter() {
	        	public void mouseClicked(MouseEvent e) { 
	        		Thread t1 = new Thread(new Runnable() {
						@Override
						public void run() {
							/*{ "单号","股票代码", "股票名称", "最新价格", "持有股数","总价","状态" };*/
							if(table.getValueAt(table.getSelectedRow(),0)!=null) {
								//单号
								StringBuffer s5 = new StringBuffer (String.valueOf(table.getValueAt(table.getSelectedRow(),0 )));
								//股票代码
								StringBuffer s1 = new StringBuffer (String.valueOf(table.getValueAt(table.getSelectedRow(), 1)));
								//股票名称
								StringBuffer s2 = new StringBuffer ((String)table.getValueAt(table.getSelectedRow(), 2));
								//最新价格
								StringBuffer s4 = new StringBuffer (String.valueOf(table.getValueAt(table.getSelectedRow(), 3)));
								//持有股数
								StringBuffer s3 = new StringBuffer (String.valueOf(table.getValueAt(table.getSelectedRow(), 4)));
								selectStock[4] = s5.toString();
								selectStock[0] = s1.toString();
								selectStock[1] = s2.toString();
								selectStock[2] = s3.toString();
								selectStock[3] = s4.toString();
								stockCode.setText(selectStock[0]);
								stockname.setText(selectStock[1]);
								stockCount.setText(selectStock[2]);
								stockBuyCount.setVisible(true);
					    		buy.setVisible(true);
							}
						}
					});
	        		t1.start();
	        	}
			});
	      //--------------------------------------------------------------------
	        JPanel panel3 = new JPanel();
	        panel3.setBounds(150,500 ,600, 120);
	        panel.add(panel3);
	        panel3.setLayout(null);
	        JLabel stockCodeLabel = new JLabel("股票代码");
	        JLabel stocknameLabel = new JLabel("股票名字");
	        JLabel stockCountLabel = new JLabel("持有股数");
	        JLabel stockBuyCountLabel = new JLabel("买出股数");	        
	        
	        Font fontstyle=new Font("黑体", Font.BOLD, 15);
	        stockCodeLabel.setFont(fontstyle);
	        stocknameLabel.setFont(fontstyle);
	        stockCountLabel.setFont(fontstyle);
	        stockBuyCountLabel.setFont(fontstyle);
	        
	        stockCodeLabel.setForeground(Color.WHITE);
	        stocknameLabel.setForeground(Color.WHITE);
	        stockCountLabel.setForeground(Color.WHITE);
	        stockBuyCountLabel.setForeground(Color.WHITE);
	        
	        
	        panel3.setOpaque(false);
	        
	        
	        panel3.add(stockCodeLabel);
	        panel3.add(stocknameLabel);
	        panel3.add(stockCountLabel);
	        panel3.add(stockBuyCountLabel);
	        stockCountLabel.setBounds(230, 0, 100, 60);
	        stockCodeLabel.setBounds(10, 0, 100, 60);
	        stocknameLabel.setBounds(120, 0, 100, 60);
	        stockBuyCountLabel.setBounds(340, 0, 100, 60);
	        stockCode = new JLabel("");
	        stockname = new JLabel("");
	        stockCount = new JLabel("");
	        stockBuyCount = new JTextField();
	        stockBuyCount.setBorder( new MyTextFieldBorder(Color.WHITE));
	        stockBuyCount.setOpaque(false);
	        stockBuyCount.setForeground(Color.WHITE);
	        buy = new MyJButtom(ImageManagerUtils.maichu);
	        stockCode.setBounds(10, 30, 100, 60);
	        stockname.setBounds(120, 30, 100, 60);
	        stockCount.setBounds(230, 30, 100, 60);
	        stockBuyCount.setBounds(340, 50, 50, 25);
	        buy.setBounds(450, 50, 110, 30);
	        stockBuyCount.setVisible(false);
	        buy.setVisible(false);
	        buy.addActionListener(this);
	        panel3.add(stockname);
	        panel3.add(stockCode);
	        panel3.add(stockCount);
	        panel3.add(stockBuyCount);
	        panel3.add(buy);
	        
	        stockname.setFont(fontstyle);
	        stockCode.setFont(fontstyle);
	        stockCount.setFont(fontstyle);
	        stockBuyCount.setFont(fontstyle);
	        
	        stockname.setForeground(Color.WHITE);
	        stockCode.setForeground(Color.WHITE);
	        stockCount.setForeground(Color.WHITE);
	        stockBuyCount.setForeground(Color.WHITE);
	        
	        
	        back=new MyJButtom(ImageManagerUtils.logoutWhiteBg);
	        back.setBounds(899, 600, 60, 60);
	        back.addActionListener(this);
	        panel.add(back,1);
		/*//------------------------------------------------------------------
		 JPanel panel3 = new JPanel();
		 panel3.setLayout(null);
		 panel3.setBounds(840,230 , 120, 300);
		 panel3.setOpaque(false);
		 panel.add(panel3);
		
		 previousPage = new JButton("上一页");
		 panel3.add(previousPage);
		 previousPage.setBounds(0, 0, 100, 60);
		 
		 nextPage = new JButton("下一页");
		 panel3.add(nextPage);
		 nextPage.setBounds(0, 120, 100, 60);*/
		setVisible(true);
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == buy) {
			if("".equals(stockBuyCount.getText())) {
				Object[] options = { "确定"}; 
				JOptionPane.showOptionDialog(null, "未输入卖出股数", "提示", 
						JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE, 
						null, options,options[0]); 
				return;
			}
			if(Integer.valueOf(selectStock[2])< Integer.valueOf(stockBuyCount.getText())) {
				Object[] options = { "确定"}; 
				JOptionPane.showOptionDialog(null, "输入卖出股数过大", "提示", 
						JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE, 
						null, options,options[0]); 
				return;
			}
			UserReal userReal = userService.checkRealnameExist(user);
			if(userReal == null) {
				Object[] options = { "确定"}; 
				JOptionPane.showOptionDialog(null, "未实名认证", "提示", 
						JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE, 
						null, options,options[0]); 
				return;
			}
			/*money = Integer.valueOf(stockBuyCount.getText()) * Double.valueOf(selectStock[3]);*/
			User user2 = userService.loginUser(user.getUsername(), user.getPassword());
			money =Double.valueOf(selectStock[3])*Integer.valueOf(stockBuyCount.getText());
			Transaction tran = new Transaction();
			tran.setTid(Integer.valueOf(selectStock[4]));
			tran.setValue(Integer.valueOf(selectStock[2])-Integer.valueOf(stockBuyCount.getText()));
			tran.setTotal(tran.getValue()*Double.valueOf(selectStock[3]));
			tran.setSid(Integer.valueOf(selectStock[0]));
			tran.setUser(user2);
			Boolean state = userService.sellStock(tran,money,Integer.valueOf(stockBuyCount.getText()));
			if(state) {
				Object[] options = { "确定"}; 
				JOptionPane.showOptionDialog(null, "出售成功", "提示", 
						JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE, 
						null, options,options[0]);
				stockCode.setText("");
				stockname.setText("");
				stockCount.setText("");
				stockBuyCount.setVisible(false);
	    		buy.setVisible(false);
				data();
				return;
			}
			
			
		}else if(e.getSource()==back) {
			this.setVisible(false);
			mainFrame.setVisible(true);;
		}
		
	}
	private void data() {
		stock.removeAll();
		List<Transaction> transactionList = userService.findUserTransaction(user);
		 /*{ "单号","股票代码", "股票名称", "最新价格", "持有股数","总价","状态" };*/
        for(Transaction tran : transactionList) {
        	Object []rowData= {tran.getTid(),tran.getStock().getScode(),tran.getStock().getSname(),tran.getStock().getFive_rise_fall(),tran.getValue(),tran.getTotal(),tran.getStock().getState()};
        	stock.addRow(rowData);
        }
        MyDefaultTableModel.setOneRowBackgroundColor(table);
	}
	

}
